﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;

namespace ModelBinder.Host.Infrastructures.ModelBinders;

public class CustomBodyWrapModelBinderProvider : IModelBinderProvider
{
    private readonly MvcOptions _options;

    public CustomBodyWrapModelBinderProvider(MvcOptions options)
    {
        _options = options;
    }

    public IModelBinder? GetBinder(ModelBinderProviderContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (context.BindingInfo.BindingSource != null && (context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Body) ||
            context.BindingInfo.BindingSource.CanAcceptDataFrom(FromCustomJsonValueAttribute.CustomJsonValue)))
        {
            var bodyModelBinderProvider = _options.ModelBinderProviders.OfType<BodyModelBinderProvider>().First()!;
            var bodyModelBinder = bodyModelBinderProvider.GetBinder(context);
            return new CustomBodyWrapModelBinder((BodyModelBinder)bodyModelBinder, new CustomJsonValueModelBinder());
        }

        return null;
    }
}